package com.code.leetcode.offer;

import com.code.leetcode.utils.TreeNode;

/**
 * @author codeDorado
 * @version 1.0
 * @date 2020/8/4 10:36
 */
public class The55_位运算_2 {
    public boolean isBalanced(TreeNode root) {
        return dfs(root) != -1;
    }

    private int dfs(TreeNode node) {
        if (node == null) return 0;
        int leftTree = dfs(node.left);
        if (leftTree == -1) return -1;
        int rightTree = dfs(node.right);
        if (rightTree == -1) return -1;

        return Math.abs(leftTree - rightTree) < 2 ? Math.max(leftTree, rightTree) + 1: -1;
    }
}
